import router from "../router/router"
import { Message } from "element-ui"
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from "../store/store"

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
    NProgress.start()
    document.title = to.meta.title
    const token = localStorage.getItem("token")
    if (to.meta.auth) {
        if (token) {
            if (to.path === "/login") {
                next({ path: '/' })
                NProgress.done()
            } else {
                 console.log("数据",store.state.user.Permissions.length)
                const hasRoles =store.state.user.Permissions.length>0 
                if (hasRoles) {
                    next()
                } else {
                    try {
                        //获取用户信息
                        const { userInfo,pagePermission } = await store.dispatch('user/getInfo')
                        //动态生成路由
                        const accessRoutes = await store.dispatch('premission/generateRoutes', {pagePermission,userInfo})
                        console.log("路由信息",accessRoutes)
                        router.addRoutes(accessRoutes)
                        next({to, replace: true })
                    } catch (error) {
                        Message.error(error || 'Has Error')
                        next(`/login?redirect=${to.path}`)
                        NProgress.done()
                    }
                }
            }
        } else {
            next({
                path: "/login",
                query: { redirect: to.path }
            })
            NProgress.done()
        }
    } else {
        next()
    }
})

router.afterEach(() => {
    NProgress.done()
})